<script setup>
import { ref, watch, computed } from 'vue'
import { SearchFiles, OpenFile, ShowInExplorer } from '../../wailsjs/go/main/App'

const props = defineProps({
  searchQuery: {
    type: String,
    default: ''
  },
  currentPath: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['item-click', 'item-double-click'])

const searchResults = ref([])
const loading = ref(false)
const error = ref('')

const hasQuery = computed(() => {
  return props.searchQuery && props.searchQuery.trim().length > 0
})

watch(() => props.searchQuery, async (newQuery) => {
  if (newQuery && newQuery.trim().length > 0) {
    await searchFiles(newQuery)
  } else {
    searchResults.value = []
  }
})

const searchFiles = async (query) => {
  if (!query.trim()) {
    searchResults.value = []
    return
  }
  
  loading.value = true
  error.value = ''
  
  try {
    const results = await SearchFiles(query, props.currentPath)
    searchResults.value = results || []
  } catch (err) {
    error.value = `搜索失败: ${err.message || err}`
    console.error('Failed to search files:', err)
  } finally {
    loading.value = false
  }
}

const handleItemClick = (node) => {
  // 单击时只发出事件，不打开文件
  emit('item-click', node)
}

const handleItemDoubleClick = async (node) => {
  if (!node.isDir) {
    try {
      await OpenFile(node.path)
    } catch (err) {
      console.error('Failed to open file:', err)
    }
  } else {
    // 双击文件夹时直接在资源管理器中打开
    try {
      await ShowInExplorer(node.path)
    } catch (err) {
      console.error('Failed to show folder in explorer:', err)
    }
  }
}

const showInExplorer = async (node) => {
  try {
    await ShowInExplorer(node.path)
  } catch (err) {
    console.error('Failed to show in explorer:', err)
  }
}

const getFileIcon = (node) => {
  if (node.isDir) {
    return 'folder'
  }
  
  const ext = node.name.split('.').pop()?.toLowerCase()
  
  // 代码文件
  const codeExts = ['js', 'ts', 'vue', 'jsx', 'tsx', 'py', 'java', 'cpp', 'c', 'h', 'cs', 'php', 'rb', 'go', 'rs', 'swift', 'kt', 'scala', 'html', 'css', 'scss', 'sass', 'less', 'json', 'xml', 'yaml', 'yml', 'toml', 'ini', 'cfg', 'conf']
  if (codeExts.includes(ext)) {
    return 'file-code'
  }
  
  // 图片文件
  const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp', 'ico']
  if (imageExts.includes(ext)) {
    return 'file-image'
  }
  
  // 视频文件
  const videoExts = ['mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv', 'webm']
  if (videoExts.includes(ext)) {
    return 'file-video'
  }
  
  // 音频文件
  const audioExts = ['mp3', 'wav', 'flac', 'aac', 'ogg', 'wma']
  if (audioExts.includes(ext)) {
    return 'file-audio'
  }
  
  // PDF文件
  if (ext === 'pdf') {
    return 'file-pdf'
  }
  
  // 压缩文件
  const archiveExts = ['zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz']
  if (archiveExts.includes(ext)) {
    return 'file-archive'
  }
  
  return 'file'
}


</script>

<template>
  <div class="search-results">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <svg class="loading-icon" viewBox="0 0 24 24" fill="currentColor">
        <path d="M12,4V2A10,10 0 0,0 2,12H4A8,8 0 0,1 12,4Z" />
      </svg>
      <span>搜索中...</span>
    </div>
    
    <!-- 错误状态 -->
    <div v-else-if="error" class="error">
      <svg class="error-icon" viewBox="0 0 24 24" fill="currentColor">
        <path d="M13,13H11V7H13M13,17H11V15H13M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z" />
      </svg>
      <span>{{ error }}</span>
    </div>
    
    <!-- 空搜索结果 -->
    <div v-else-if="hasQuery && searchResults.length === 0" class="empty">
      <svg class="empty-icon" viewBox="0 0 24 24" fill="currentColor">
        <path d="M9.5,3A6.5,6.5 0 0,1 16,9.5C16,11.11 15.41,12.59 14.44,13.73L14.71,14H15.5L20.5,19L19,20.5L14,15.5V14.71L13.73,14.44C12.59,15.41 11.11,16 9.5,16A6.5,6.5 0 0,1 3,9.5A6.5,6.5 0 0,1 9.5,3M9.5,5C7,5 5,7 5,9.5C5,12 7,14 9.5,14C12,14 14,12 14,9.5C14,7 12,5 9.5,5Z" />
      </svg>
      <span>未找到匹配的文件</span>
    </div>
    
    <!-- 搜索结果 -->
    <div v-else-if="hasQuery" class="results-content">
      <div class="search-header">
        <span class="search-count">找到 {{ searchResults.length }} 个结果</span>
      </div>
      
      <div class="results-list">
        <div 
          v-for="node in searchResults" 
          :key="node.path" 
          class="result-item"
        >
          <div 
            class="item-content"
            :class="{ 'is-directory': node.isDir }"
            @click="handleItemClick(node)"
            @dblclick="handleItemDoubleClick(node)"
            @contextmenu.prevent="showInExplorer(node)"
          >
            <div class="item-icon">
              <svg v-if="getFileIcon(node) === 'folder'" class="icon" viewBox="0 0 24 24" fill="currentColor">
                <path d="M10,4H4C2.89,4 2,4.89 2,6V18A2,2 0 0,0 4,20H20A2,2 0 0,0 22,18V8C22,6.89 21.1,6 20,6H12L10,4Z" />
              </svg>
              <svg v-else-if="getFileIcon(node) === 'file-code'" class="icon" viewBox="0 0 24 24" fill="currentColor">
                <path d="M14.6,16.6L19.2,12L14.6,7.4L16,6L22,12L16,18L14.6,16.6M9.4,16.6L4.8,12L9.4,7.4L8,6L2,12L8,18L9.4,16.6Z" />
              </svg>
              <svg v-else-if="getFileIcon(node) === 'file-image'" class="icon" viewBox="0 0 24 24" fill="currentColor">
                <path d="M8.5,13.5L11,16.5L14.5,12L19,18H5M21,19V5C21,3.89 20.1,3 19,3H5A2,2 0 0,0 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19Z" />
              </svg>
              <svg v-else class="icon" viewBox="0 0 24 24" fill="currentColor">
                <path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z" />
              </svg>
            </div>
            
            <div class="item-info">
              <div class="item-name">{{ node.name }}</div>
              <div class="item-path">{{ node.path }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.search-results {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.loading, .error, .empty {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  gap: 12px;
  padding: 40px 20px;
  color: var(--text-secondary);
  text-align: center;
}

.loading-icon, .error-icon, .empty-icon {
  width: 48px;
  height: 48px;
  opacity: 0.6;
}

.loading-icon {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.error {
  color: var(--error-color, #ef4444);
}

.results-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.search-header {
  padding: 12px 16px;
  border-bottom: 1px solid var(--border-color);
  background: var(--bg-secondary);
  font-size: 14px;
  color: var(--text-secondary);
}

.results-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

.result-item {
  margin: 0 8px 4px;
}

.item-content {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid transparent;
}

.item-content:hover {
  background: var(--hover-bg);
  border-color: var(--border-hover);
}

.item-content.is-directory {
  font-weight: 500;
}

.item-icon {
  flex-shrink: 0;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon {
  width: 16px;
  height: 16px;
  color: var(--icon-color);
}

.item-content.is-directory .icon {
  color: var(--folder-color, #3b82f6);
}

.item-info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.item-name {
  font-size: 14px;
  color: var(--text-primary);
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: left;
}

.item-path {
  font-size: 12px;
  color: var(--text-secondary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  opacity: 0.8;
  text-align: left;
}

/* 浅色主题 */
.light-theme .search-results {
  --bg-primary: #ffffff;
  --bg-secondary: #f8f9fa;
  --text-primary: #1a1a1a;
  --text-secondary: #6b7280;
  --border-color: #e5e7eb;
  --border-hover: #d1d5db;
  --hover-bg: #f3f4f6;
  --icon-color: #6b7280;
  --folder-color: #3b82f6;
}

/* 深色主题 */
.dark-theme .search-results {
  --bg-primary: #1a1a1a;
  --bg-secondary: #2a2a2a;
  --text-primary: #ffffff;
  --text-secondary: #a0a0a0;
  --border-color: #404040;
  --border-hover: #606060;
  --hover-bg: #2a2a2a;
  --icon-color: #a0a0a0;
  --folder-color: #60a5fa;
}
</style>